<template>
  <a-modal
      style="top: 1px;"
      :title="title"
      :width="width"
      v-model="visible"
      :confirmLoading="confirmLoading"
      :keyboard="false"
      :maskClosable="false"
  >
    <template #footer>
      <a-button key="back" @click="handleCancel">
        关闭
      </a-button>
      <a-button key="submit" v-show="oktext" type="primary" :loading="loading" @click="handleOk">
        {{oktext}}
      </a-button>
    </template>
    <a-spin :spinning="confirmLoading">
      <div >
        <a-form>
          <a-row :getter="24">
            <a-col :span="6">
              <a-form-item label="登记人" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <a-input v-model="main.create_by" disabled placeholder="自动生成"></a-input>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <div>
        <a-button class="editable-add-btn" icon="plus" @click="handleAdd" v-show="!readOnly">
          添加
        </a-button>
        <!-- <a-button type="primary" @click="showInfo">信息</a-button> -->
        <a-table bordered size="small" width="50%" :data-source="dataSource" :columns="filterColumns(columns)"  :customHeaderRow="headerClick(columns,0)"
                 :pagination="false" rowKey="key" :scroll="{ y: 350 }" :customRow="toggleEdit">
          <!-- 搜索-->
          <template #matid="{ text, record, index }">
            <YG-editable-cell ref="matid" :record="record" :text="text" :supplierDict="supplierDict" :dia="dia" :search="arr_editable[index] && !record['matid']"  @change="onCellChange(index, record, 'matid', $event)" />
          </template>
          <template #matname="{ text, record, index }">
            <YG-editable-cell ref="matname" :record="record" :text="text" :supplierDict="supplierDict" :dia="dia" :search="arr_editable[index] && !record['matid']"  @change="onCellChange(index, record, 'matname', $event)" />
          </template>
          <!-- 非搜索-->
          <template #matpprice="{ text, record, index }">
            <YG-editable-cell ref="matpprice" type="float" :text="text" :editable="arr_editable[index]" @getSum="getSum(index, record, 'matpprice', $event)" @done="advance('matpprice')"/>
          </template>
          <template #matqty="{ text, record, index }">
            <YG-editable-cell ref="matqty" type="number" :text="text" :editable="arr_editable[index]" @getSum="getSum(index, record, 'matqty', $event)" @done="advance('matqty')" />
          </template>
          <template #matvalidity="{ text, record, index }">
            <YG-editable-cell ref="matvalidity" type="string" :text="text" :editable="arr_editable[index]" @done="advance('matvalidity')"/>
          </template>
          <template #matbatid="{ text, record, index }">
            <YG-editable-cell ref="matbatid" :text="text" :editable="arr_editable[index]" @done="advance('matbatid')"/>
          </template>
          <!--other-->
          <template #supplier="{ text, record, index }">
            <span>{{supplierDict[text]||text}}</span>
          </template>
          <template #operation="{ text, record, index }">
            <a v-if="arr_editable[index]" href="javascript:void(0);" title="暂存" @click="toggle(index,false)"><a-icon type="save" /></a>
            <a v-else href="javascript:void(0);" title="编辑" @click="toggle(index,true)"><a-icon type="edit" /></a>
            <a-popconfirm
                v-if="dataSource.length"
                title="是否确认删除?"
                @confirm="() => onDelete(index)"
            >
              <a style="padding-left:6px" href="javascript:void(0);" title="删除"><a-icon type="delete" /></a>
            </a-popconfirm>
          </template>
        </a-table>
      </div>
    </a-spin>
  </a-modal>
</template>

<script setup>
import { ref, reactive, nextTick, watch, computed } from 'vue';
import { getAction, postAction } from '@/utils/request';
import YGEditableCell from '@/components/YGCrm/YGEditableCell.vue';
import moment from 'moment';
import { filterColumns, headerClick } from '@/utils/my'; // 假设这两个函数来自 @/utils/my

const props = defineProps(['type', 'record']);
const emit = defineEmits(['close', 'sync']);

const arr_editable = ref(new Array(100));
const selectedKeys = ref([]);
const dia = reactive({
  visible: false,
  filter: {},
  dataSource: [],
  selectedRowKeys: [],
  dfType: 'main',
  columns: {
    main: [
      {
        title: '#',
        dataIndex: '',
        // ... 其他 columns 配置 ...
      },
      // ... 其他 main 列配置 ...
    ]
  }
});
const keyNumber = ref(0);
const disableMixinCreated = ref(true);
const loading = ref(false);
const title = ref('操作');
const width = ref('90%');
const visible = ref(false);
const count = ref(0);
const fetching = ref(false);
const Data = ref([]);
const Add = reactive({
  selectMat: '',
  qty: 0,
  listProject: [],
  listmatcondep: []
});
const main = reactive({
  create_by: '',
  store: '',
  supplier: '',
  matflag: '0',
  matuse: 'ZR',
  matbillid: '',
  matbilldate: undefined,
  matbillno: '',
  matcondep: '' // 领用科室
});
const readOnly = ref(false); // 是否可以编辑
const invoicable = ref(false); // 可以补发
const oktext = ref('');
const labelCol = reactive({
  xs: { span: 24 },
  sm: { span: 5 }
});
const wrapperCol = reactive({
  xs: { span: 24 },
  sm: { span: 16 }
});
const confirmLoading = ref(false);
const url = reactive({
  save: '/material/matstoremain/save',
  listDetail: '/material/matstore/list'
});
const columns = ref([
  {
    title: '#',
    dataIndex: '',
    key: 'rowIndex',
    width: '3%',
    align: 'center',
    customRender: function(t, r, index) {
      return parseInt(index) + 1
    }
  },
  // ... 其他列配置 ...
]);
const dataSource = ref([]);

const inputColumns = computed(() => {
  return columns.value.filter(c => {
    // 输入框跳转，顺序以 columns 实际顺序为准；是否为可跳转输入框，以 editable 为准
    return !(c.is_show === 0) && c['editable'];
  });
});

const advance = (refname) => {
  let len = inputColumns.value.length;
  let index_cur = inputColumns.value.findIndex(c => refname === c.dataIndex);
  if (len === 0 || index_cur === -1) {
    console.error("can't find refname");
    return;
  }
  if (index_cur === len - 1) {
    handleAdd();
  } else {
    nextTick(() => {
      let newRef = inputColumns.value[index_cur + 1].dataIndex;
      console.log("newRef:" + newRef);
      console.log(this.$refs);
      if (this && this.$refs && newRef) this.$refs[newRef].$refs.inputCell.focus();
    });
  }
};

const toggle = (index, status) => {
  arr_editable.value.splice(index, 1, status);
};

const dtChange = (date, dateString) => {
  console.log(date, dateString, main.matbilldate);
  main.matbilldate = dateString;
};

const m = (dt, ft) => {
  if (!dt) return undefined;
  return moment(dt, ft);
};

const getSum = (index, record, key, $event) => {
  let sum = 0;
  if (key === 'matpprice') {
    record['matpprice'] = $event;
    sum = $event * record['matqty'];
  }
  if (key === 'matqty') {
    record['matqty'] = $event;
    sum = $event * record['matpprice'];
  }
  sum = sum.toFixed(2);
  nextTick(() => {
    if (!isNaN(sum)) record['matsum'] = sum;
  });
  //console.error(JSON.stringify(record));
};

const onCellChange = (index, row, key, val) => {
  //  添加会少列问题，字段没信息问题已解决->是因为 rowkey 主键有问题
  //submit
  if (val === '@submit') {
    let { dataSource, selectedRowKeys } = dia;
    // 去自身和空记录;去已选记录
    dataSource.value.splice(index, 1);
    for (let i = dataSource.value.length - 1; i >= 0; i--) {
      if (!dataSource.value[i].matid.trim()) {
        dataSource.value.splice(i, 1);
      }
    }

    selectedRowKeys && selectedRowKeys.forEach((i) => {
      addNewRow(dataSource.find(d => d['__row_number__'] === i));
    });
    // 进入非编辑状态
    arr_editable.value = new Array(100);
    dia.selectedRowKeys = [];
    // 第一个数据量为 0 的，进入编辑状态
    let i = dataSource.value.findIndex(d => !d['matqty']);
    arr_editable.value[i] = true;
    arr_editable.value.splice(i, 1, true);
    // "this.arr_editable"初始化后，导致"dia.visible"也初始化，要重新搞(等 render 完成,重新给值)
    nextTick(() => {
      dia.visible = false;
      advance('matname');
    });
    return;
  }

  //query
  if (!main.store) {
    console.error('请选择库房');
    return;
  }
  if (!val.trim()) {
    console.error('请输入搜索关键字');
    return;
  }
  let { current: pageNo, pageSize } = dia.pagination;
  nextTick(() => {
    dia.visible = true;
  });

  let filter = {};
  if (key === "matname" && /[a-zA-Z]+/.test(val)) {
    filter['matpinyin'] = val;
  } else {
    filter[key] = val;
  }
  selectedKeys.value = dataSource.value.map((row) => {
    return row.matid;
  }).filter(item => item !== "");

  dia.filter = filter;
  dia.selectedRowKeys = [];
  dia.dataSource = [];

  // 已选,已选的不要
  getMatProjectByFilters(main.store, dia.filter, selectedKeys.value, pageNo, pageSize, (res) => {
    if (res && res[0]) {
      dia.dataSource = res;
      dia.pagination.total = res[0].sum || res[0].total;
    }
  });
  //console.error(JSON.stringify(that.dia.dataSource));
};

const onDelete = (index) => {
  // 先清再给，解决部分不更新的情况
  let ds = JSON.parse(JSON.stringify(dataSource.value));
  dataSource.value = [];
  ds.splice(index, 1);
  arr_editable.value.splice(index, 1);
  nextTick(() => {
    dataSource.value = ds;
  });
};

const handleAdd = () => {
  addNewRow({});
  let len = dataSource.value.length;
  arr_editable.value = new Array(100);
  arr_editable.value.splice(len - 1, 1, true);

  nextTick(() => {
    if (main.store) {
      if (this.$refs.matid.$refs.inputCell) {
        this.$refs.matid.$refs.inputCell.focus();
      }
    } else {
      this.$refs.store.focus();
    }
  });
};

const toggleEdit = (record, index) => {
  return {
    on: {
      dblclick: () => {
        if (readOnly.value) return;
        for (let i = 0; i < arr_editable.value.length; i++) {
          if (i !== index) arr_editable.value[i] = false;
        }
        arr_editable.value.splice(index, 1, !arr_editable.value[index]);
      }
    }
  };
};

const addNewRow = (mat) => {
  if (!mat) return;
  ++keyNumber.value;
  const newData = {
    matitemid: '',
    matmanufacturer: mat.MatProUnits,
    matid: mat.MatId,
    matname: mat.MatName,
    matmodel: mat.MatModel,
    matspecifications: mat.Matspecifications,
    matunit: mat.MatBasicUnit,
    matqty: '',
    matsum: 0,
    matpprice: mat.MatRPPrice,
    matprice: mat.MatRPrice,
    matvalidity: '',
    matbatid: '',
    __row_number__: mat.__row_number__,
    key: keyNumber.value
  };
  // 去重,重复的不要;防止 sql 缓存产生的重复
  if (!newData.matid || selectedKeys.value.indexOf(newData.matid) === -1) {
    dataSource.value.push(newData);
  } else {
    console.error(newData.matname + '已选择！请勿重复');
  }
};

const setFormData = (record) => {
  if (record.matbillid) {
    main.matbillid = record.matbillid;
    main.store = record.matstore;
    main.supplier = record.mathapunit;
    main.matflag = record.matflag;
    main.matcondep = record.matcondep;
    invoicable.value = record.invoicable;
    let res = columns.value.find(c => c['dataIndex'] === 'operation');
    if (!readOnly.value) {
      res.is_show = 1;
      oktext.value = "保存";
    } else {
      res.is_show = 0;
      oktext.value = "";
    }
    main.matuse = record.matuse;
    main.matbillno = record.matbillno;
    main.matbilldate = !record.matbilldate ? undefined : moment(record.matbilldate, 'YYYY-MM-DD');
    main.matcondep = record.matcondep;
  } else {
    readOnly.value = false;
    oktext.value = "保存";
    main.store = '';
    main.supplier = '';
    main.matflag = '0';
    main.matuse = 'ZR';
    main.matbillid = '';
    main.matbilldate = undefined;
    main.matbillno = '';
    main.matcondep = ''; // 领用科室
  }
};

const checkStoreData = () => {
  if (dataSource.value.length < 1) {
    console.error('没有要保存的数据');
    return false;
  }
  for (let i = 0; i < dataSource.value.length; i++) {
    let row = dataSource.value[i];
    let qty = parseFloat(row.matqty, 10);
    if (qty <= 0) {
      console.error(`第${i + 1}行的数量为 0，不能保存`);
      return false;
    }
  }
  if (main.store) {
  } else {
    console.error("请选择库房!");
    return false;
  }
  if (main.supplier) {
  } else {
    console.error("请选择供应商!");
    return false;
  }
  return true;
};

const getDetailList = (record) => {
  if (record.matbillid) {
    let param = {
      id: record.matbillid
    };
    loading.value = true;
    getAction(url.listDetail, param).then((res) => {
      if (res.success) {
        let list = res.result;
        for (let i = 0; i < list.length; i++) {
          ++keyNumber.value;
          let row = list[i];
          row.key = keyNumber.value;
        }
        dataSource.value = list;
        loading.value = false;
      } else {
        console.error('读取采购入库单明细错误');
        loading.value = false;
      }
    });
  }
};

const add = () => {
  dataSource.value = [];
  readOnly.value = false;
  edit({});
  handleAdd();
};

const edit = (record) => {
  // initialize
  arr_editable.value = new Array(100);
  selectedKeys.value = [];
  //console.error(JSON.stringify(record))
  visible.value = true;
  if (record.matflag) readOnly.value = record.matflag === "1";
  nextTick(() => {
    setFormData(record);
    getDetailList(record);
    if (invoicable.value) {
      // $("#invoice").focus(); 这里可能需要调整为 Vue 3 的方式
    }
  });
};

const close = () => {
  emit('close');
  visible.value = false;
};

const handleCancel = () => {
  close();
};

const handleOk = () => {
  if (readOnly.value) {
    close();
    //this.$message.error('该单已执行不能修改！保存失败!')
    return;
  }
  if (!checkStoreData()) { // 检查数据
    return;
  }
  let option = '';
  if (main.matbillno === undefined || main.matbillno === '') {
    option = 'CG';
  } else {
    option = 'ZR';
  }
  let MatStoreClient = {
    matbillid: main.matbillid,
    matstore: main.store,
    supplier: main.supplier,
    matcondep: main.matcondep,
    matuse: main.matuse,
    matoperation: option,
    matbillno: main.matbillno,
    matbilldate: main.matbilldate,
    matpay: '03',
    matflag: main.matflag
  };
  let list = [];
  let numberRreg = /^\+?[1-9][0-9]*$/;
  for (let i = 0; i < dataSource.value.length; i++) {
    let item = dataSource.value[i];
    // 不是选的材料不算有效记录
    if (!item.__row_number__) continue;
    // 无数量的不算有效记录
    if (!numberRreg.test(item.matqty)) continue;
    let mat = {
      matitemid: item.matitemid,
      matid: item.matid,
      matqty: item.matqty,
      matvalidity: item.matvalidity,
      matbatid: item.matbatid,
    };
    list.push(mat);
  }
  MatStoreClient.list = list;
  let id = main.matbillid;
  saveOrUpdate(id, MatStoreClient);
};

const saveOrUpdate = (id, MatStoreClient) => {
  console.log("data:" + JSON.stringify(MatStoreClient));
  postAction(url.save, MatStoreClient).then((res) => {
    if (res.success) {
      console.log('保存成功');
      emit("sync", id || res.result);
      console.log("sync...");
      close();
    } else {
      console.error('保存失败');
      console.log('错误原因', res.message);
    }
  });
};

watch(dataSource, (newValue, oldValue) => {
  // 处理 dataSource 变化
}, { deep: true });
</script>

<style>

</style>